package com.example.controller;

import com.example.entity.Result;
import com.example.entity.Student;
import com.example.service.StudentService;
import com.example.utils.ResultUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author John
 */
@RequestMapping("/Student")
@RestController
public class StudentController {

    @Resource
    private StudentService studentService;

    @GetMapping("/showTable")
    public Object getTable(@RequestParam("limit") Integer limit, @RequestParam("offset") Integer offset) {
        return studentService.pageShow(limit, offset);
    }


    @GetMapping("/findTable")
    public Result getTable1(@RequestParam(value = "limit", defaultValue = "3") Integer
                                    limit, @RequestParam(value = "offset", defaultValue = "4") Integer offset) {
        JSONObject jsonObject = new JSONObject();
        PageHelper.startPage(limit, offset);
        List<Student> studentlist = studentService.all();
        PageInfo<Student> pageInfo = new PageInfo<>(studentlist);
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", pageInfo.getTotal());
        jsonObject.put("data", studentlist);
        return ResultUtils.success(jsonObject);
    }


    @ApiOperation(value = "插入一个学生")
    @PostMapping("/insert")
    public Result<Integer> insert(@RequestBody Student student) {
        return ResultUtils.success(studentService.insert(student));
    }

    @ApiOperation(value = "删除一个学生")
    @DeleteMapping("/deleteById")
    public Result<Integer> deleteById(@RequestParam("id") String id) {
        return ResultUtils.success(studentService.deleteById(id));
    }

    @ApiOperation(value = "更新一个学生")
    @PutMapping("/update")
    public Result<Integer> update(@RequestParam("id") String id, @RequestParam("oldid") String oldid, @RequestParam("name") String name, @RequestParam("sex") String sex, @RequestParam("age") String age) {
        return ResultUtils.success(studentService.update(oldid, id, name, sex, age));
    }

    @ApiOperation(value = "通过Id查询一个学生")
    @GetMapping("/searchById")
    public Result<Integer> searchById(@RequestParam("id") String id) {
        return ResultUtils.success(studentService.searchById(id));
    }

}

